//
//  TranRecordCard.swift
//  ptbuy
// 交易记录页面
//  Created by MyMac on 2024/12/4.
//

import SwiftUI
import CoreData

struct TranRecordCard: View {
    
    
    @Environment(\.managedObjectContext) private var viewContext
    
    @EnvironmentObject var appDelegate: AppDelegate // 引用 AppDelegate
    
    @ObservedObject var clientPojo:Client
    @Binding var isProgressLoading:Bool
    @Binding var totalPrice:Int64
    @Binding var totalProduct:Int16
    
    @State private var tranProduct:Bool = false//跳转查看商品界面
    
    @State private var isModifyClientFailAlert:Bool = false//修改失败提示
    @State private var isDeleteClientAlert:Bool = false//删除提示
    @State private var isDeleteClientFailAlert:Bool = false//删除失败提示
    @State private var tranRecordCard:Bool = false//修改框
    //导出签字确认单
    @State private var goToSigna:Bool = false//去签名
    @State private var exportFail:Bool = false//导出失败提示
    @State private var signaTip:Bool = false//导出签名提示 [是否客户签名确认]
    @State private var isSigna:Bool = false//客户是否已经签名
    @State private var productArr:[ProductPojo] = []//查询出来的商品信息
    @State private var clientSignPath:String = ""//客户签名文件
    
    //查看签字确认单
    @State private var navigateToDetail:Bool = false
    @State private var navigateToDetailFail:Bool = false
    @State private var fileName:String = ""
    @State private var clientId:String = ""
    @State private var clientName:String = ""
    @State private var clientPhone:String = ""
    @State private var clientAgentName:String = ""
    
    var body: some View {
        
        VStack{
            HStack{
                Spacer()
                Button(
                   action: {
                       searchExport(clientId:clientId,type: 0)
                   }) {
                       Text("查看签字确认单") .font(.system(size: 15))
                       
                   }.alert("还未导出签字确认单",isPresented: $navigateToDetailFail){
                       Button("关闭",role: .cancel){
                           navigateToDetailFail = false
                       }
                   }
                   .buttonStyle(
                       MyButtonStyle(width:130,size:15,height: 30)
                   )
                Spacer()
                Button(
                   action: {
                       signaTip = true
                      fileName = ""
                      searchExport(clientId:clientId,type: 1)
                   }) {
                       Text("导出签字确认单") .font(.system(size: 15))
                   }.alert("数据查询失败",isPresented: $exportFail){
                       Button("关闭",role: .cancel){
                           exportFail = false
                       }
                   }.alert("是否客户签名确认",isPresented: $signaTip){
                       Button("否",role: .cancel){
                           signaTip = false
                           isProgressLoading = true
                           //直接查询导出
                           exportSign(clientId:clientId)
                           
                       }
                       Button("签名",role: .destructive){
                           //如果需要重新签名，则判断以前有没有签名，没有重新签，有则覆盖以前单签名
                           signaTip = false
                           goToSigna = true
                           isProgressLoading = true
                           clientSignPath = ""
                       }
                   }.alert("客户未签名",isPresented: $isSigna){
                       Button("关闭",role: .cancel){
                           isSigna = false
                       }
                   }
                   .buttonStyle(
                       MyButtonStyle(width:130,size:15,height: 30)
                   )
                // 通过 NavigationLink 跳转页面
                NavigationLink(destination: SignatureView(clientSignPath: $clientSignPath), isActive: $goToSigna) {
                    EmptyView()
                }
                Spacer()
            }
            Divider()
            HStack{
                Text("客户姓名:") .font(.system(size: 15))
                Spacer()
                Text(clientPojo.name ?? "") .font(.system(size: 15))
            }
            Divider()
            HStack{
                Text("客户电话:") .font(.system(size: 15))
                Spacer()
                Text(clientPojo.phone ?? "") .font(.system(size: 15))
            }
            Divider()
            HStack{
                Text("收  购  人:") .font(.system(size: 15))
                Spacer()
                Text(clientPojo.agent_name ?? "") .font(.system(size: 15))
            }
            Divider()
            HStack{
                Text("总  件  数:") .font(.system(size: 15))
                Spacer()
                Text("\(clientPojo.total_product)件") .font(.system(size: 15))
            }
            Divider()
            HStack{
                Text("总      价:") .font(.system(size: 15))
                Spacer()
                Text("\(clientPojo.total_price)元") .font(.system(size: 15))
            }
            Divider()
            HStack{
                Text("记录时间:") .font(.system(size: 15))
                Spacer()
                Text(clientPojo.time ?? "") .font(.system(size: 15))
            }
            Divider()
            
            HStack{
                Spacer()
                Button(
                   action: {
                       isDeleteClientAlert = true
                   }) {
                       Text("删除") .font(.system(size: 15))
                       
                   }.alert("是否确认删除？",isPresented:$isDeleteClientAlert){
                        Button("关闭", role: .cancel) {
                            isDeleteClientAlert = false
                        }
                        Button("删除", role: .destructive) {
                            removeClient(item:clientPojo)
                            isDeleteClientAlert = false
                        }
                    }.alert("删除失败",isPresented:$isDeleteClientFailAlert){
                        Button("关闭", role: .cancel) {
                            isDeleteClientFailAlert = false
                        }
                    }
                   .buttonStyle(
                       MyButtonStyle(width:100,size:15,height: 30)
                   )
                Spacer()
                Button(
                   action: {
                       tranRecordCard = true
                   }) {
                       Text("修改") .font(.system(size: 15))
                       
                   }.alert("修改失败",isPresented:$isModifyClientFailAlert){
                       Button("关闭", role: .cancel) {
                           isModifyClientFailAlert = false
                       }
                   }
                   .buttonStyle(
                       MyButtonStyle(width:100,size:15,height: 30)
                   )
                Spacer()
                Button(
                   action: {
                       tranProduct = true
                   }) {
                       Text("查看商品") .font(.system(size: 15))
                   }
                   .buttonStyle(
                       MyButtonStyle(width:100,size:15,height: 30)
                   )
                // 通过绑定控制跳转
                    NavigationLink(
                        destination: TranProductView(modigyClient:clientPojo,tranProduct:$tranProduct),
                        isActive: $tranProduct,
                        label: {
                            EmptyView() // 不显示任何内容
                        }).navigationBarBackButtonHidden()
                Spacer()
            }.onAppear{
                if let id = clientPojo.id{
                    clientId = id
                }
                if let name = clientPojo.name{
                    clientName = name
                }
                if let agentName = clientPojo.agent_name{
                    clientAgentName = agentName
                }
                if let phone = clientPojo.phone{
                    clientPhone = phone
                }
                if clientSignPath.isEmpty{
                    if let signatureFilePath = clientPojo.signatureFilePath{
                        clientSignPath = signatureFilePath
                    }
                }
               
                appDelegate.unlockOrientation()
                if  goToSigna{
                    goToSigna = false
                    Task{
                         // 延时1秒等待视图回正
                        try? await Task.sleep(nanoseconds: 1 * 1_500_000_000)
                                  
                        if clientSignPath != ""{
                            exportSign(clientId: clientId)
                        }else{
                            isSigna = true
                            isProgressLoading = false
                        }
                     }
                    
                   
                }
                
            }.fullScreenCover(isPresented: $navigateToDetail){
                PdfViewer(fileName: $fileName,isPresented: $navigateToDetail)
            }.fullScreenCover(isPresented: $tranRecordCard){
                TranRecordModifyView(tranRecordCard: $tranRecordCard,modigyClient: clientPojo,isModifyClientFailAlert:$isModifyClientFailAlert)
            }
            
        }.padding()
    }
    
    
        /*
         通过客户ID查询导出的信息
         type:0、查看签字确认单 1、点击导出签字确认单的时候判断;3、删除信息
         */
    func searchExport(clientId:String,type:Int8){
        let request: NSFetchRequest<Export> = Export.fetchRequest()
        // 设置查询条件，例如查询 amount > 10
        request.predicate = NSPredicate(format: "clientid = %@",clientId)
        do {
                    // 执行查询并将结果存储在 fetchedItems 中
           let exports = try viewContext.fetch(request)
            
            if exports.count==0 && type == 0{
                navigateToDetailFail = true
            }
            
            for object in exports {
                
                if type==3{
                    viewContext.delete(object)
                }else{
                    if let path = object.exportFilePath{
                        if path.contains(".pdf"){
                            fileName  = path
                            if type==0{
                                navigateToDetail = true
                            }
                        }
                    }
                }
            }
            if type==3{
                try viewContext.save()
            }
        } catch {
            if type==3{
                isDeleteClientFailAlert = true
            }else{
                if type==0{
                    navigateToDetailFail = true
                    print("Error fetching data: \(error)")
                }
            }
        }
    }
    //导出PDF
    func exportSign(clientId:String){
        
        let request: NSFetchRequest<Product> = Product.fetchRequest()
               // 设置查询条件，例如查询 amount > 10
        request.predicate = NSPredicate(format: "pid = %@",clientId)
        do{
            let products = try viewContext.fetch(request)
            
            productArr.removeAll()

           for object in products {
               let productName : String = object.product_name ?? ""
               let time : String = object.time ?? ""
               productArr.append(ProductPojo(product_name: productName,
                                              product_price: String(object.product_price),
                                             time: time,clientName:clientName,clientPhone:clientPhone,
                                             clientAgentName:clientAgentName))
           }
            Task{
                
                fileName =   try await createPDF(product:productArr,
                                                 clientSignPath:clientSignPath,
                                                 myFileName:fileName,
                                                 isSign:true)
              
                navigateToDetail = true
                isProgressLoading = false
                
                //删除导出信息
                searchExport(clientId: clientId, type: 3)
                //保存导出信息
                saveExport()
                
                //这里修改了签名信息，所以需要修改数据库的签名文件路径
                clientPojo.signatureFilePath = clientSignPath
                do{
                    try viewContext.save()
                }catch{
                    
                }
            }
            
            
        }catch{
            exportFail = true
            isProgressLoading = false
        }
    }
    
    //保存签字确认单
    private func saveExport(){
        let export = Export(context:viewContext)
        export.id = UUID().uuidString
            .replacingOccurrences(of: "-", with: "")// 或者其他类型，确保是唯一的标识
        print(clientId)
        export.clientid = clientId
        export.exportFilePath = fileName
        export.exportDate = formattedDate()
        do{
            try viewContext.save()
        }catch{
            print("Error saving context: \(error.localizedDescription)")
        }
    }
    // 创建日期格式化器
    func formattedDate() -> String {
        let formatter = DateFormatter()
        // 获取当前时间
        let currentDate = Date()
        formatter.dateStyle = .long
        formatter.timeStyle = .medium
        return formatter.string(from: currentDate)
    }
    //删除客户信息
    func  removeClient(item:Client){
        
        let request: NSFetchRequest<Product> = Product.fetchRequest()
               // 设置查询条件，例如查询 amount > 10
        request.predicate = NSPredicate(format: "pid = %@",clientId)
        
        do{
            let products = try viewContext.fetch(request)
            
            productArr.removeAll()
            
            //先删除商品信息
            for object in products {
                clientPojo.managedObjectContext?.delete(object)
            }
            
            //删除成功后计算商品总件数和总价
             totalProduct -= 1
   
             totalPrice = totalPrice - Int64(item.total_price)
            
            //删除导出信息
            searchExport(clientId: clientId, type: 3)
            
            if !isDeleteClientFailAlert{
                clientPojo.managedObjectContext?.delete(item)
              
                try clientPojo.managedObjectContext?.save()
            }
            
           
            
        }catch{
            isDeleteClientFailAlert = true
        }
    }

}

